const router = require('koa-router')()
const util = require('../utils/index.js')
const Role = require('../models/roleSchema.js')

router.prefix('/api/role')

// 获取所有角色列表
router.get('/allList', async (ctx) => {
    try {
        const list = await Role.find({}, '_id roleName')
        ctx.body = util.success(list, '')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

// 获取角色列表
router.get('/list', async (ctx) => {
    const { roleName } = ctx.request.query
    const { page, skipIndex } = util.pager(ctx.request.query)
    try {
        let params = {}
        if (roleName) params.roleName = roleName
        const query = Role.find(params)
        const list = await query.skip(skipIndex).limit(page.pageSize)
        const total = await Role.countDocuments(params)
        ctx.body = util.success({
            list,
            page: {
                ...page,
                total
            }
        }, '')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

// 新增
router.post('/add', async (ctx, next) => {
    try {
        const { roleName, remark } = ctx.request.body
        let res = await Role.create({ roleName, remark })
        ctx.body = util.success({}, '创建成功')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

// 编辑
router.post('/update', async (ctx, next) => {
    try {
        const { _id, roleName, remark } = ctx.request.body
        let params = { roleName, remark }
        params.updateTime = new Date()
        let res = await Role.findByIdAndUpdate(_id, params)
        ctx.body = util.success({}, '更新成功')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

// 删除
router.post('/delete', async (ctx, next) => {
    try {
        const { _id } = ctx.request.body
        let res = await Role.findByIdAndRemove(_id)
        ctx.body = util.success({}, '删除成功')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

// 权限设置
router.post('/update/permission', async (ctx) => {
    const { _id, permissionList } = ctx.request.body
    try {
        let params = { permissionList, update: new Date() }
        let res = await Role.findByIdAndUpdate(_id, params)
        ctx.body = util.success({}, '权限设置成功')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

module.exports = router
